
import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_modular/flutter_modular.dart';
import 'package:thinking/config/_.dart';
import 'package:thinking/entity/_.dart';
import 'package:thinking/utils/_.dart';
import 'package:thinking/views/Dynamic/DynamicItem.dart';
import 'package:thinking/widget/_.dart';
import 'package:thinking/service/_.dart';
class PersonalTopItem extends StatefulWidget{

  @override
  _PersonalTopItem createState() => _PersonalTopItem(userId: userId,pageIndex: pageIndex,username: Uri.decodeComponent(userName));

  final int userId;
  final int pageIndex;
  final String userName;
  PersonalTopItem({required this.userId,required this.pageIndex,required this.userName});

}

class _PersonalTopItem extends State<PersonalTopItem>{

  List<String> topItem = ['动态','关注','粉丝'];

   int userId;
   int pageIndex;
   late Future<dynamic> _function;
    List<DynamicDataEntity> dynamicList =[];
    List<UserData> userList=[];
   PageEntity pageEntity = PageEntity();
  String username;
  EasyRefreshController _easyRefreshController = EasyRefreshController();
  _PersonalTopItem({required this.userId,required this.pageIndex,required this.username});


  Widget easyRefresh(Widget child) {
    return EasyRefresh(
      child: child,
      header: BezierCircleHeader(backgroundColor: ColorConfig.ThemeColor),
      footer: BezierBounceFooter(backgroundColor: ColorConfig.ThemeColor),
      enableControlFinishRefresh: false,
      enableControlFinishLoad: true,
      controller: _easyRefreshController,
      bottomBouncing: true,
      onLoad: () async {
        if (pageEntity.canLoad){
          pageEntity.setPage = pageEntity.page + 1;
        }
        await getData();
        _easyRefreshController.finishLoad(success: true);
      },
    );
  }

  @override
  void initState() {
    super.initState();
    _function = future();
  }

  future() async{
    await getData();
  }

  Future<void> getData() async{
    switch(pageIndex){
      case 0:
        return await getDynamicData();
      default:
        return await getUserData();
    }
  }

  Future<void> getDynamicData() async{
    List<DynamicDataEntity> res =
    (  await UserService.getUserDynamic(params: {
      'dynamic_Page':pageEntity.page,
      'dynamic_Count':pageEntity.count,
      'user_Id':userId,
      'my_Id':SPreferences().getInt('user_Id')
    })).dynamicList!;
    if (!pageEntity.canLoad) {
      BotToast.showText(text: '没有更多动态了哦~');
    }
    if (res.length < pageEntity.count && pageEntity.canLoad) {
      pageEntity.setPage = pageEntity.page +1;
      pageEntity.setCanLoad = false;
    }
    dynamicList = [...dynamicList,...res];
    setState(() {

    });

  }
  Future<void> getUserData() async{

    List<UserData> res =
    (  await UserService.getUserFollowOrFans(params: {
      'user_Page':pageEntity.page,
      'user_Count':pageEntity.count,
      'user_Id':userId,
      'my_Id':SPreferences().getInt('user_Id'),
      'isFollowData':pageIndex==1
    })).userList!;
    if (!pageEntity.canLoad) {
      BotToast.showText(text: '没有更多用户了哦~');
    }
    if (res.length < pageEntity.count && pageEntity.canLoad) {
      pageEntity.setPage = pageEntity.page +1;
      pageEntity.setCanLoad = false;
    }
    userList = [...userList,...res];
    setState(() {

    });

  }

  @override
  void dispose() {
    _easyRefreshController.dispose();
    super.dispose();
  }

Widget title(){
    return Row(
      children: [
          IconButton(onPressed: (){

            Modular.to.pop();

          }, icon: Icon(Icons.arrow_back),color: ColorConfig.WhiteBackColor,iconSize: 20,),
        Text(
          userId == SPreferences().getInt('user_Id')?'我的'+ topItem[pageIndex]:'$username的' + topItem[pageIndex],
          style: TextStyle(
              color: ColorConfig.WhiteBackColor,
              fontSize: 16,
            fontWeight: FontWeight.bold
          ),
        )
      ],
    );
}



 @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          backgroundColor: ColorConfig.ThemeColor,
          automaticallyImplyLeading: false,
          elevation: 0,
          title: title(),

        ),
        body: FutureBuilder(
          future: _function,
          builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
          return snapshot.connectionState == ConnectionState.done?Container(
            child: easyRefresh(
              Empty(

                  child: ListView(
                physics: BouncingScrollPhysics(),
                shrinkWrap: true,
                children: pageIndex == 0?dynamicList.asMap().keys.map((e) => Column(
                  children: [
                    Visibility(child: Line(),visible:e!=0),
                    DynamicItem(
                      dynamicData: dynamicList[e],
                      key: ValueKey(dynamicList[e].dynamicId),
                    )
                  ],
                )).toList():userList.map((e) => GestureDetector(
                  onTap: (){
                    if(e.userId != SPreferences().getInt('user_Id'))Modular.to.pushNamed('/personal/${e.userId}');
                  },
                  child: UserItemWidget(userData: e,showButton: e.userId != SPreferences().getInt('user_Id'),),
                ),).toList(),
              ),
              isShow: pageIndex == 0?dynamicList.length == 0:userList.length == 0,
              )
            ),
          ):Loading();
        },

        ),
    );
  }

}